package leetcode.editor.template.sort;

/**
 * 归并排序
 */
public class MergeSortTest {
    public static void main(String[] args) {
        // 调用
        int[] nums = {3, 4, 1, 5, 2, 1};
        MergeSortTest mergeSortTest = new MergeSortTest();
        mergeSortTest.mergeSort(nums, 0, nums.length - 1);
        for (int num : nums) {
            System.out.print(num);
        }
    }

    /**
     * 归并排序
     *
     * @param nums
     * @param l
     * @param r
     */
    void mergeSort(int[] nums, int l, int r) {
        // 终止条件
        if (l >= r) {
            return;
        }

        int mid = (l + r) / 2;
        mergeSort(nums, l, mid);
        mergeSort(nums, mid + 1, r);

        int[] tmp = new int[r - l + 1]; // 暂时保存元素
        for (int i = l; i <= r; i++) {
            tmp[i - l] = nums[i];
        }

        int i = 0, j = mid - l + 1;
        for (int k = l; k <= r; k++) {
            if (i == mid - l + 1) {
                nums[k] = tmp[j++];
            } else if (j == r - l + 1 || tmp[i] <= tmp[j]) {
                nums[k] = tmp[i++];
            } else if (tmp[i] > tmp[j]) {
                nums[k] = tmp[j++];
            }
        }
    }
}
